package com.jt.zcdemo.handler;

import com.lowagie.text.pdf.BaseFont;
import freemarker.cache.StringTemplateLoader;
import freemarker.template.Configuration;
import freemarker.template.Template;
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang3.text.WordUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.xhtmlrenderer.pdf.ITextRenderer;

import java.io.*;
import java.nio.charset.StandardCharsets;
import java.util.Map;

/**
 * @author Administrator
 * @version 1.0
 * @description: TODO
 * @date 2024/12/21 19:38
 */
@Component
public class PdfHelper {

    /**
     * classpath路径
     */
    private String classpath = getClass().getResource("/").getPath();

    /**
     * 指定FreeMarker模板文件的位置
     */
    private String templatePath = "/templates";

    /**
     * freeMarker模板文件名称
     */
    private String templateFileName = "pdf.ftl";

    /**
     * 图片路径 —— 默认是classpath下面的images文件夹
     */
    private String imagePath = "/images/";

    /**
     * 字体资源文件 存放路径
     */
    private String fontPath = "fonts/";

    /**
     * 字体   [宋体][simsun.ttc]   [黑体][simhei.ttf]
     */
    private String font = "simsun.ttc";

    /**
     * 指定编码
     */
    private String encoding = "UTF-8";

    @Value("{$file.path}")
    private String filePath;

    /**
     * 生成pdf
     *
     * @param data 传入到freemarker模板里的数据
     * @param out  生成的pdf文件流
     */
    public void createPDF(Map<String, Object> data, OutputStream out, String templateName) throws Exception {
        // 创建一个FreeMarker实例, 负责管理FreeMarker模板的Configuration实例
        Configuration cfg = new Configuration(Configuration.DEFAULT_INCOMPATIBLE_IMPROVEMENTS);
        // 指定FreeMarker模板文件的位置
        ITextRenderer renderer = new ITextRenderer();
        String simsun = System.getProperty("user.dir") + "/simsun.ttc";
       // String arialuni = System.getProperty("user.dir") + "/arialuni.ttf";
        File fondFile = new File(simsun);
        if (!fondFile.exists()) {
            getFondPath();
        }
        // 设置 css中 的字体样式（暂时仅支持宋体和黑体）
        renderer.getFontResolver().addFont(simsun, BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);
        //renderer.getFontResolver().addFont(arialuni, BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);

        StringTemplateLoader stringLoader = new StringTemplateLoader();
        String templateString = getFileData("templates/" + templateName);
        stringLoader.putTemplate("myTemplate", templateString);
        cfg.setTemplateLoader(stringLoader);
        Template tpl = cfg.getTemplate("myTemplate", "utf-8");
        StringWriter writer = new StringWriter();

        // 把null转换成""
        //Map<String, Object> dataMap = CommunalTool.objectToMap(data);
        // 将数据输出到html中
        tpl.process(data, writer);
        writer.flush();

        String html = writer.toString();
        // 把html代码传入渲染器中
        renderer.setDocumentFromString(html);

        renderer.layout();
        renderer.createPDF(out, false);
        renderer.finishPDF();
        out.flush();
        out.close();

    }

    // 读取jar中的ftl模版文件
    private String getFileData(String path) {
        InputStream stream = getClass().getClassLoader().getResourceAsStream(path);
        // log.info("infile:"+infile);
        StringBuffer sb = new StringBuffer();
        BufferedReader br = null;
        try {
            br = new BufferedReader(new InputStreamReader(stream, "UTF-8"));
            String s = null;
            while ((s = br.readLine()) != null) {
                sb.append(s);
            }
            br.close();
            return sb.toString();
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        } finally {
            if (br != null) {
                try {
                    br.close();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
    }

    /**
     * 获取字体路径
     *
     * @return
     * @throws IOException
     */
    private String getFondPath() throws IOException {
        String fontPath = System.getProperty("user.dir");
        InputStream inputStream = getClass().getClassLoader().getResourceAsStream("fonts/simsun.ttc");
        //在根目录生成一个文件
        File targetFile = new File(fontPath + "/simsun.ttc");
        // //将流转成File格式
        FileUtils.copyInputStreamToFile(inputStream, targetFile);

        InputStream arialuniStream = getClass().getClassLoader().getResourceAsStream("fonts/arialuni.ttf");
        File arialuni = new File(fontPath + "/arialuni.ttf");
        FileUtils.copyInputStreamToFile(arialuniStream, arialuni);
        return fontPath;
    }

    public void setClasspath(String classpath) {
        this.classpath = classpath;
    }


    public void setTemplatePath(String templatePath) {
        this.templatePath = templatePath;
    }


    public void setTemplateFileName(String templateFileName) {
        this.templateFileName = templateFileName;
    }


    public void setImagePath(String imagePath) {
        this.imagePath = imagePath;
    }


    public void setFontPath(String fontPath) {
        this.fontPath = fontPath;
    }


    public void setFont(String font) {
        this.font = font;
    }


    public void setEncoding(String encoding) {
        this.encoding = encoding;
    }


    public  void generateWord(Map<String, Object> dataMap, String templateName, String fileName) throws Exception {

        // 设置FreeMarker的版本和编码格式
        Configuration configuration = new Configuration(Configuration.DEFAULT_INCOMPATIBLE_IMPROVEMENTS);
        configuration.setDefaultEncoding("UTF-8");

        // 设置FreeMarker生成Word文档所需要的模板的路径
        // configuration.setDirectoryForTemplateLoading(new File("/Users/xxx/Desktop/"));
        // 此处把模版文件都放在 resources 下的 templates 中
        configuration.setClassForTemplateLoading(WordUtils.class, "/templates");

        // 设置FreeMarker生成Word文档所需要的模板
        Template tem = configuration.getTemplate(templateName, "UTF-8");
        // 创建一个Word文档的输出流
        Writer out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(new File(fileName)), StandardCharsets.UTF_8));
        // FreeMarker使用Word模板和数据生成Word文档
        tem.process(dataMap, out);
        out.flush();
        out.close();
    }

}
